<template>
	<view class="searchLayout">
		<view class="searchForm">
			<uni-search-bar :focus="true" v-model="query.keyword" placeholder="搜索" 
			@cancel="clear" @confirm="onsearch" @clear="clear">
			</uni-search-bar>
		</view>
		<!-- 占位view -->
		<view :style="{height: (getTitleBarHeight() + 20) + 'px'}"></view>
		<view class="section" v-if="!images.length">
			<view class="title">
				<text class="text">最近搜索</text>
				<uni-icons type="trash" class="icon" size="20" @click="clearKeywords"></uni-icons>
			</view>
			<view class="list">
				<uni-tag v-for="(item, index) in lastest" :key="index" 
				:text="item" inverted circle class="tag" @click="search(item)"/>
			</view>
		</view>
		<view class="section" v-if="!images.length">
			<view class="title">
				<text class="text">热门搜索</text>
			</view>
			<view class="list">
				<uni-tag v-for="(item, index) in hots" :key="index" 
				:text="item" inverted circle class="tag" @click="search(item)"/>
			</view>
		</view>
		<view class="content" v-if="images.length">
			<view class="item" v-for="(item, index) in images" :key="item._id" @click="goDetail(item._id)">
				<image :src="cloudIdToUrl(item.picurl,{w:'200rpx',h:'450rpx'})" mode="aspectFill" class="pic" :class="{ 'loaded': item.isLoaded }" @load="handleImageLoad(item)"></image>
			</view>
		</view>
		<uni-load-more :status="status"></uni-load-more>
	</view>
</template>

<script setup>
	import {ref} from 'vue'
	import { apiGetImageList } from '@/api/index.js'
	import { cloudIdToUrl } from '@/utils/common.js'
	import { onUnload, onReachBottom } from '@dcloudio/uni-app'
	import { getTitleBarHeight } from '@/utils/system.js'
	
	
	const hots = ref([' AI ','美女','帅哥','宠物','卡通'])
	const lastest = ref([])
	const images = ref([])
	


	try {
		const ks = uni.getStorageSync('keywords');
		if (ks) {
			lastest.value = ks
		}
	} catch (e) {
		// error
	}
	
	const query = ref({
		keyword: '',
		pageNum: 1,
		pageSize: 12
	})
	const status = ref('no-more')
	const onsearch = (e)=>{
		search(e.value)
	}
	// 查询
	const search = async (keyword)=> {
		if(keyword) query.value.keyword = keyword.trimStart().trimEnd()
		if(query.value.keyword) {
			if(lastest.value.indexOf(query.value.keyword) < 0) {
				lastest.value.push(query.value.keyword)
				uni.setStorageSync('keywords', lastest.value)
			} 
			status.value = 'loading'
			const data = await apiGetImageList(query.value)
			if(data.list.length > 0) {
				let temps = data.list.map(item=>{
					return {
						...item,
						isLoaded:false
					}
				})
				images.value = [...images.value, ...temps]
				
				// 存储images数组
				let arrs = images.value.map(item=>{
					return item
				})
				uni.setStorageSync('priviews',arrs)
				status.value = 'more'
			}else {
				query.value.pageNum--
				status.value = 'noMore'
				if(images.length) {
					uni.showToast({
						icon:'error',
						title:'没有更多数据了'
					})
				}
			}
		}
	}
	
	const clearKeywords = () => {
		lastest.value = []
		images.value = []
		uni.removeStorageSync('keywords')
		uni.removeStorageSync('priviews')
	}
	
	const clear = () => {
		images.value = []
		uni.removeStorageSync('priviews')
		status.value = 'no-more'
	}
	
	onReachBottom(()=>{
		if(status.value != 'noMore'){
			query.value.pageNum ++
			search()
		}
	})
	
	// 通过样式与在数据中增加isLoaded字段，处理图片太大或网络太慢导致有图片未加载问题
	const handleImageLoad = (item) => {
		item.isLoaded = true // 加载完成后更新状态
	}
	
	const goDetail = (id)=>{
		uni.navigateTo({
			url:"/pages/preview/preview?id="+id
		})
	}
	
	// 销毁页面时，清理缓存
	onUnload(()=>{
		clearKeywords()
	})
	
	
</script>

<style lang="scss" scoped>
	.searchLayout{
		position: relative;
		.searchForm{
			position: fixed;  // 固定定位
			left: 0;
			width: 100%;
			z-index: 10;    // 确保在最上层
			background: #fff; // 添加背景色
			box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05); // 可选阴影效果
		}
		.section{
			padding: 20rpx;
			.title{
				display: flex;
				justify-content: space-between;
				align-items: center;
				.text{
					color: $text-color-grey;
				}
				.icon{
					font-size: 40rpx;
				}
			}
			.list{
				padding: 20rpx 0;
				display: flex;
				flex-wrap: wrap; // 允许换行
				gap: 20rpx; // 元素间距
				align-items: flex-start; // 顶部对齐
				.tag{
					color: $text-color-mian;
				}
			}
		}
		.noData{
			height: 400rpx;
			width: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
			color: $text-color-grey;
			font-size: 24rpx;
		}
		.content{
			padding: 5rpx;
			display: grid;
			row-gap: 5rpx;  // 纵向间距
			column-gap: 5rpx; // 横向间距
			grid-template-columns: repeat(3, 1fr);
			.item{
				height: 440rpx;
				background: #f0f0f0 no-repeat center;
				.pic{
					height: 100%;
					width: 100%;
					display: block;
				}
				.loaded {
				  opacity: 1;
				  transition: opacity 0.3s;
				}
			}
			
		}
	}
</style>
